package com.aizhixin.lab.docker.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Component
@Slf4j
public class IoUtils {

    @Value("${file.upload}")
    private String uploadUrl;
    @Value("${file.download}")
    private String downloadUrl;
    @Value("${file.shell}")
    private String shellPath;

    public ResponseEntity<Map> uploadFile(String host, String port, String dir, String fileName, byte[] data){
        String uploadFileUrl = "http://"+host+":"+port+uploadUrl;
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        Resource resource = new ByteArrayResource(data){
            @Override
            public String getFilename() {
                return fileName;
            }
        };
        MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
        form.add("file", resource);
        form.add("dir",dir);
        form.add("filename",fileName);
        HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(form, headers);
        ResponseEntity<Map> re = restTemplate.postForEntity(uploadFileUrl, files, Map.class);
        log.info(fileName+"文件上传结果："+fileName);
        return re;

    }

    public ResponseEntity<byte[]> downLoadFile(String host, String port, String dir, String fileName){
        String downloadFileUrl = "http://"+host+":"+port+downloadUrl;
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<byte[]> responseEntity = restTemplate.getForEntity(downloadFileUrl+"?dir="+dir+"&filename="+fileName, byte[].class);
        log.info("respone headers :"+responseEntity.getHeaders().toString());
        return responseEntity;
    }


    public ResponseEntity<Map> exeShell(String cmd, String host, String port){
        String shellUrl = "http://"+host+":"+port+shellPath+"?shell="+cmd;
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<Map> body = restTemplate.exchange(shellUrl, HttpMethod.GET,null, Map.class);
        return body;
    }
}
